import React, { useState, useRef, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom'
import { Modal, message } from "antd";
import captchaStyles from './SliderCaptcha.module.css'
import styles from './login.module.css'
import http from '../utils/http'
const Tuo = ({ onSuccess, onFail }) => {
  const [loading, setLoading] = useState(true);
  const [bgImage, setBgImage] = useState('');
  const [puzzlePiece, setPuzzlePiece] = useState('');
  const [puzzlePos, setPuzzlePos] = useState({ x: 40, y: 80 });
  const [sliderValue, setSliderValue] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const [startX, setStartX] = useState(0);
  const [message, setMessage] = useState('');
  const [sessionId] = useState(`captcha_${Date.now()}_${Math.random().toString(36).substr(2, 8)}`);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false)
  const navigate = useNavigate();
  const containerRef = useRef(null);
  const sliderRef = useRef(null);
  const puzzleRef = useRef(null);
  const holeRef = useRef(null);
  // 初始化验证码
  const initCaptcha = useCallback(async () => {
    setLoading(true);
    setMessage('');
    setSliderValue(0);
    try {
      // 随机确定拼图位置 (x: 40-260, y: 80)
      const newX = Math.floor(Math.random() * 220) + 40;
      const newY = 80;
      setPuzzlePos({ x: newX, y: newY });
      const imageUrl = `https://picsum.photos/300/200?random=${sessionId}`;
      setBgImage(imageUrl);
      await new Promise(resolve => setTimeout(resolve, 800));
      setPuzzlePiece(imageUrl);

      // 设置拼图块背景显示位置
      if (puzzleRef.current) {
        puzzleRef.current.style.backgroundPosition = `-${newX}px -${newY}px`;
      }

      setLoading(false);
    } catch (error) {
      console.error('验证码加载失败:', error);
      setMessage('加载失败，请重试');
      setLoading(false);
    }
  }, [sessionId]);
  // 拖拽开始
  const handleDragStart = (e) => {
    if (loading || isDragging) return;

    setIsDragging(true);
    const clientX = e.clientX || e.touches[0].clientX;
    setStartX(clientX - sliderValue);

    document.body.style.userSelect = 'none';
    document.body.style.cursor = 'grabbing';
    setMessage('');
  };
  // 拖拽移动
  const handleDragMove = (e) => {
    if (!isDragging || loading) return;

    const clientX = e.clientX || e.touches[0].clientX;
    const containerLeft = containerRef.current?.getBoundingClientRect().left || 0;
    const sliderWidth = sliderRef.current?.offsetWidth || 300;
    const pieceWidth = 40;

    let newPos = clientX - startX - containerLeft;
    newPos = Math.max(0, Math.min(newPos, sliderWidth - pieceWidth));

    setSliderValue(newPos);
  };
  // 拖拽结束
  const handleDragEnd = () => {
    if (!isDragging || loading) return;

    setIsDragging(false);
    document.body.style.userSelect = '';
    document.body.style.cursor = '';

    // 验证位置(允许±3px误差)
    const tolerance = 3;
    const isVerified = Math.abs(sliderValue - puzzlePos.x) <= tolerance;

    if (isVerified) {
      setMessage('验证成功！');
      onSuccess?.();
      setTimeout(() => {
        navigate('/');
      }, 1500);
    } else {
      setMessage('验证失败，请重试');
      onFail?.();
      setTimeout(() => {
        initCaptcha();
      }, 1000);
    }
  };
  // 全局事件监听
  useEffect(() => {
    const handleGlobalMouseUp = () => {
      if (isDragging) handleDragEnd();
    };
    const handleGlobalMouseMove = (e) => {
      handleDragMove(e);
    };
    document.addEventListener('mouseup', handleGlobalMouseUp);
    document.addEventListener('touchend', handleGlobalMouseUp);
    document.addEventListener('mousemove', handleGlobalMouseMove);
    document.addEventListener('touchmove', handleGlobalMouseMove);

    return () => {
      document.removeEventListener('mouseup', handleGlobalMouseUp);
      document.removeEventListener('touchend', handleGlobalMouseUp);
      document.removeEventListener('mousemove', handleGlobalMouseMove);
      document.removeEventListener('touchmove', handleGlobalMouseMove);
      document.body.style.userSelect = '';
      document.body.style.cursor = '';
    };
  }, [isDragging, handleDragMove]);
  // 初始化
  useEffect(() => {
    initCaptcha();
  }, [initCaptcha]);
  const handleLogin = () => {
    http.post('/list', { username, password })
      .then(res => {
        console.log(res.data);
        if (res.data.code === 200){
          setIsModalOpen(true); 
          localStorage.setItem('token', JSON.stringify(res.data.accessToken))  
        } else {
          alert(res.data.message);
          initCaptcha();
        }
      })
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  return (
    <div className={styles.loginContainer}>
      <div className={styles.loginHeader}>
        <h1 className={styles.loginTitle}>欢迎回来</h1>
        <p className={styles.loginSubtitle}>请登录您的账号</p>
      </div>
      
      <div>
        <div className={styles.formGroup}>
          <label className={styles.formLabel}>账号</label>
          <input 
            type='text' 
            value={username} 
            onChange={(e) => { setUsername(e.target.value) }} 
            className={styles.formInput} 
            placeholder="请输入账号"
          />
        </div>
        <div className={styles.formGroup}>
          <label className={styles.formLabel}>密码</label>
          <input 
            type='password' 
            value={password} 
            onChange={(e) => { setPassword(e.target.value) }} 
            className={styles.formInput} 
            placeholder="请输入密码"
          />
        </div>
      </div>

      <div>
        <Modal title="安全验证" open={isModalOpen} onCancel={handleCancel}>
          <div className={captchaStyles.puzzleCaptcha} ref={containerRef}>
            <div>
              <div className={captchaStyles.captchaHeader}>
                <h3>请拖动滑块完成拼图</h3>
                <button
                  onClick={initCaptcha}
                  disabled={loading}
                  className={captchaStyles.refreshBtn}
                >
                  {loading ? '加载中...' : '刷新验证码'}
                </button>
              </div>
              <div className={captchaStyles.imageContainer}>
                {loading ? (
                  <div className={captchaStyles.loading}>正在加载验证码...</div>
                ) : (
                  <>
                    <div className={captchaStyles.bgImageContainer}>
                      <img src={bgImage} alt="验证背景" className={captchaStyles.bgImage} />
                      <div
                        ref={holeRef}
                        className={captchaStyles.puzzleHole}
                        style={{
                          left: `${puzzlePos.x}px`,
                          top: `${puzzlePos.y}px`,
                          width: '40px',
                          height: '40px'
                        }}
                      />
                    </div>

                    <div
                      ref={puzzleRef}
                      className={captchaStyles.puzzlePiece}
                      style={{
                        backgroundImage: `url(${puzzlePiece})`,
                        left: `${sliderValue}px`,
                        top: `${puzzlePos.y}px`,
                        width: '40px',
                        height: '40px'
                      }}
                    />
                  </>
                )}
              </div>
              <div className={captchaStyles.sliderContainer} ref={sliderRef}>
                <div
                  className={`${captchaStyles.sliderHandle} ${isDragging ? captchaStyles.dragging : ''}`}
                  style={{ left: `${sliderValue}px` }}
                  onMouseDown={handleDragStart}
                  onTouchStart={handleDragStart}
                >
                  <svg viewBox="0 0 24 24" width="18" height="18">
                    <path d="M9 16h6v-6h-6zm-6 0h6v-6H3zm12-6h6V4h-6z" fill="currentColor" />
                  </svg>
                </div>
                <div className={captchaStyles.sliderTrack}>
                  <div className={captchaStyles.sliderProgress} style={{ width: `${sliderValue}px` }} />
                  <div className={captchaStyles.sliderText}>
                    {sliderValue === 0 ? '向右滑动完成拼图' : ''}
                  </div>
                </div>
              </div>
              {message && (
                <div className={`${captchaStyles.message} ${message.includes('成功') ? captchaStyles.success : captchaStyles.error}`}>
                  {message}
                  {message.includes('成功') && (
                    <svg viewBox="0 0 24 24" width="16" height="16">
                      <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z" fill="currentColor" />
                    </svg>
                  )}
                </div>
              )}
            </div>
          </div>
        </Modal>
      </div>
      <div>
        <button className={styles.loginButton} onClick={() => { handleLogin() }}>登录</button>
      </div>
      
      <div className={styles.bottomLinks} style={{  position: 'fixed', /* 固定定位 */
            bottom: '15px'  }}>
        还没有账号？
        <a className={styles.linkText} onClick={() => { navigate('/enroll') }}>注册</a>
        <span className={styles.divider}>|</span>
        <a className={styles.linkText} onClick={() => { navigate('/plogin') }}>手机号登录</a>
        <span className={styles.divider}>|</span>
        <a onClick={()=>{
              localStorage.removeItem('token');
              navigate('/')
        }}>点击游客登陆</a> 
      </div>
    </div>
  );
};

export default Tuo;